#include "stdafx.h"
#include "SettingsManager.h"
#include <fstream>
#include <assert.h>

SettingsManager::SettingsManager(void)
{
	// load the settings file
	fstream file("Settings.ini", ios::in);

	assert(file.is_open() && "No settings file found!");
	// begin reading file contents

	while (file.good())
	{
		// read a line from the file
		string line;
		getline(file, line);

		if (line.empty())
			continue; // empty line

		string::size_type offset = line.find_first_of('=');
		
		// extract key, value pair
		string key = line.substr(0, offset);
		string value = line.substr(offset + 1, line.size());

		// detirmine the type of the setting
		if (value[0] >= 48 && value[0] < 58)
		{
			// this value is an integral or decimal type
			string::size_type decimal_index = value.find_first_of('.');
			if (decimal_index == string::npos) // no decimal found, it's an int
			{
				Setting s(key.c_str(), atoi(value.c_str()));
				settings.push_back(s);
			}
			else // if a decimal was found, it's a float
			{
				Setting s(key.c_str(), stof(value));
				settings.push_back(s);
			}
		}
		else // its a string
		{
			Setting s(key.c_str(), value.c_str(), value.size());
			settings.push_back(s);
		}
	}

	// close the file
	file.close();
}

SettingsManager::~SettingsManager(void)
{

}

void SettingsManager::setSetting(const char* name, Setting* value)
{
	for (unsigned int i = 0; i < settings.size(); i++)
		if (strcmp(settings[i].name.c_str(), name) == 0)
		{
			settings[i] = *value;
			return;
		}
}

/*static*/ SettingsManager* SettingsManager::GetInstance(void)
{
	static SettingsManager instance;

	return &instance;
}

Setting SettingsManager::getSetting(const char* name) const
{
	for (unsigned int i = 0; i < settings.size(); i++)
		if (strcmp(settings[i].name.c_str(), name) == 0)
			return settings[i];

	assert("Failed to find setting");
	return Setting("", "", 0);
}